#!/bin/sh
#
# chkconfig:	345 85 15
# description:	FastCGI server for Django


# Source function library
if [ -f /lib/lsb/init-functions ]; then
	. /lib/lsb/init-functions
fi
# Source networking configuration.
if [ -f /etc/sysconfig/network ]; then
	. /etc/sysconfig/network
fi
# Check that networking is up.
# [ "${NETWORKING}" = "no" ] && exit 0

PROJ=pywebnmj					# Django project name
PROJSPATH=/usr/share/pyshared			# The folder Django project is in
SOCKSPATH=/tmp					# Where you put UNIX socket file
PIDSPATH=/var/run				# Where you put .pid file
RUNAS=ecolleu					# Set a different user to run the FastCGI server

SRVNAME=$PROJ				# Process name

# Maximum requests for a child to service before expiring
#MAXREQ=
# Spawning method - prefork or threaded
#METHOD=
# Maximum number of children to have idle
#MAXSPARE=
# Minimum number of children to have idle
#MINSPARE=
# Maximum number of children to spawn
#MAXCHILDREN=

start () {
	# Check if the service is already running?
	if [ ! -f $PIDSPATH/$SRVNAME.pid ]; then
		echo -n $"Starting $SRVNAME..."
		start-stop-daemon --start --pidfile=$PIDSPATH/$SRVNAME.pid --name $PROJ --user $RUNAS --startas $PROJSPATH/$PROJ/manage.py runserver
		echo
		#chmod 777 $SOCKSPATH/$SRVNAME.sock
		RETVAL=$?
	else
		echo $"$SRVNAME is already running."
	fi
}

stop() {
	# Stop daemons.
	if [ -f $PIDSPATH/$SRVNAME.pid ]; then
		echo -n $"Stopping $SRVNAME..."
		start-stop-daemon --stop --pidfile=$PIDSPATH/$SRVNAME.pid --name $PROJ --retry=TERM/30/KILL/5
		echo
		# Delete pidfile only when Django was called successfully
		if [ $? -eq 0 ]; then
			rm -f $PIDSPATH/$SRVNAME.pid "$SRVNAME.pid"  >/dev/null 2>&1
		fi
	else
		echo $"$SRVNAME is NOT running."
	fi

}

RETVAL=0

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	status)
		status -p "$PIDSPATH/$SRVNAME.pid" $SRVNAME
		RETVAL=$?
		;;
	restart)
		stop
		start
		;;
	*)
		echo $"Usage: $0 {start|stop|restart|status}"
		exit 3
		;;
esac

exit $RETVAL
